import json

from flask import Flask, render_template, request, jsonify

import log_helper
from config_manager import ConfigManager
from decorator import api_call
from config import Config
from device_manager import DeviceManager
from script_utils import execute_script

logger = log_helper.init_logging("bgw")
app = Flask(__name__)
config_manager = ConfigManager()
device_manager = DeviceManager(config_manager)


def get_config_data():
    """获取配置数据"""
    # 使用 ConfigManager.get_all_param() 获取配置
    all_params = config_manager.get_all_param()
    
    # 参数映射关系：前端参数名 -> get_all_param()中的参数名
    param_mapping = {
        '__GNB_IP__': 'gnbSctp_IP',
        '__AMF_IP__': 'amfSctp_IP', 
        '__UPF_IP__': 'upf_IP',
        '__MCC__': 'mcc',
        '__MNC__': 'mnc',
        '__TAC__': 'tac',
        '__IPSEC_IP__': 'ipsec_IP'
    }
    
    # 构建返回的配置对象
    config = {}
    for frontend_param, config_param in param_mapping.items():
        if config_param in all_params:
            # 如果配置参数存在，使用配置参数值
            config[frontend_param] = all_params[config_param]
        else:
            # 如果配置参数不存在，使用空字符串
            config[frontend_param] = ''
    
    return config


@app.route('/')
def index():
    """Web页面入口"""
    return render_template('index.html')


@app.route("/receive", methods=['POST', 'GET'])
@api_call
def call():
    request_text = request.get_data(as_text=True)
    if not request_text:
        logger.error("接收参数为空")
        return {"_status": 1, "_msg": "接受参数为空"}
    # JSON格式校验
    try:
        request_cmd = json.loads(request_text)
        logger.info(f"接收到请求: {request_text}")
    except json.JSONDecodeError as e:
        logger.error(f"JSON格式错误: {str(e)}")
        return {"_status": 1, "_msg": f"JSON格式错误: {str(e)}"}
    # cmdType校验
    cmd_type = request_cmd.get('cmdType')
    if not cmd_type:
        logger.error("缺少cmdType参数")
        return {"_status": 1, "_msg": "缺少cmdType参数"}
    if cmd_type == 'getConfig':
        return get_config_data()
    elif cmd_type == 'updateConfig':
        params = request_cmd.get('params', {})
        results = config_manager.update_params(params)
        return results
    elif cmd_type == 'device':
        params = request_cmd.get('params', {})
        return device_manager.handle_device_command(params)
    elif cmd_type == 'status':
        # 执行状态检查脚本
        return execute_script(Config.status_script_path)
    elif cmd_type == 'start':
        # 执行启动脚本
        return execute_script(Config.start_script_path)
    elif cmd_type == 'stop':
        # 执行停止脚本
        return execute_script(Config.stop_script_path)
    return {"_status": 1, "_msg": "cmdType错误"}





if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8500, debug=True)
